package com.framework.network.interceptor.commoninter

import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.internal.checkOffsetAndCount
import okio.BufferedSink
import java.io.IOException
import java.nio.charset.StandardCharsets.UTF_8

/**
 * @ClassName: PostJsonBody
 * @Description:
 * @Author: you
 */
class PostJsonBody(val content: String) : RequestBody() {

    override fun contentType(): MediaType? {
        return JSON
    }

    @Throws(IOException::class)
    override fun writeTo(sink: BufferedSink) {
        val bytes = content.toByteArray(charset)
        checkOffsetAndCount(bytes.size.toLong(), 0, bytes.size.toLong())
        sink.write(bytes, 0, bytes.size)
    }

    companion object {
        private val JSON = "application/json; charset=utf-8".toMediaTypeOrNull()
        private val charset = UTF_8

        fun create(content: String): RequestBody {
            return PostJsonBody(content)
        }
    }
}
